using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Commons.Models.Settings.Serialization
{
	[Serializable]
	public class SerializableSortedDictionary<K,V> : SortedDictionary<K,V>, ISerializable
	{
		public SerializableSortedDictionary() : base()
		{

		}

		private SerializableSortedDictionary(SerializationInfo info, StreamingContext context)
		{
			K[] keys = (K[])info.GetValue("keys", typeof(K[]));
			V[] values = (V[])info.GetValue("values", typeof(V[]));

			if (keys.Length != values.Length)
			{
				throw new SerializationException("keys and values does not match");
			}

			for (int i=0; i<keys.Length; i++)
			{
				Add(keys[i], values[i]);
			}
		}

		#region ISerializable implementation

		public void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			K[] keys = new K[Count];
			V[] values = new V[Count];

			Keys.CopyTo(keys, 0);

			for(int i=0; i<Count; i++)
			{
				values[i] = this[keys[i]];
			}

			info.AddValue("keys", keys);
			info.AddValue("values", values);
		}

		#endregion
	}
}

